<template>
	<view class="add-address">
		<view class="agent-form">
			<view class="form-card">
				<view class="card-title">编辑地址信息</view>
		
				<view class="form">
					<view class="form-item">
						<view class="form-label">联系人<text style="color: red;">*</text></view>
						<view class="form-body">
							<view class="input">
								<input type="text" v-model="formData.linkman" placeholder="请输入您的真实姓名" placeholder-class="placeholder-class" />
							</view>
						</view>
					</view>
					<view class="form-item">
						<view class="form-label">手机号<text style="color: red;">*</text></view>
						<view class="form-body">
							<view class="input">
								<input type="number" :maxlength="11" v-model="formData.phone" placeholder="请输入您的真实手机号" placeholder-class="placeholder-class" />
							</view>
						</view>
					</view>
					<view class="form-item">
						<view class="form-label">所在地区<text style="color: red;">*</text></view>
						<view class="form-body">
							<view class="input" @click="openArea">
								<input type="text" disabled :value="formData.province ? `${formData.province}/${formData.city}/${formData.area}` : ''" placeholder="请选择所在区域省、市、县区"  placeholder-class="placeholder-class" />
								<view class="iconfont icon-chevron-down"></view>
							</view>
						</view>
					</view>
					<view class="form-item">
						<view class="form-label">详细地址<text style="color: red;">*</text></view>
						<view class="form-body">
							<view class="input">
								<input type="text" v-model="formData.address" :disabled="!formData.address"  @click.stop="chooseLocation(false)" placeholder="请输入详细地址" placeholder-class="placeholder-class" />
								<view class="right-btn" @click.stop="chooseLocation(true)">定位</view>
							</view>
						</view>
					</view>
					<view class="form-item">
						<view class="form-label">设为默认地址<text style="color: red;">*</text></view>
						<view class="form-body">
							<view class="radio-group">
								<label class="f-radio" :class="{'f-is-checked': item.value === formData.is_default}" v-for="item in options7" :key="item.value" @click="changeType(item, 'is_default')">
									<input type="radio" name="sex" :data-value="item.value" disabled class="f-radio_former" :value="item.value" data-allow-uncheck="true" />
									<text class="f-radio_input"></text>
									<text class="f-radio_label">{{ item.label }}</text>
								</label>
							</view>
						</view>
					</view>
					
					<view class="form-item">
						<view class="form-body flex align-center" style="gap: 16rpx;border-bottom: none;padding-top: 16rpx;">
							<button class="confirm-btn flex-1" @click="submit">保存</button>
							<button v-if="editId" class="cancel-btn flex-1" @click="handleDelete">删除</button>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<area-picker ref="area" @change="handleSeleteArea"></area-picker>
	</view>
</template>

<script>
	const checker = require("@/utils/checker.js");
	import AddressParse from 'address-parse';
	import provinceData from '@/libs/city-data/province.js';
	import cityData from '@/libs/city-data/city.js';
	import areaData from '@/libs/city-data/area.js';
	
	
	export default {
		data() {
			return {
				formData: {
					linkman: '', // string 姓名 必需
					phone: '', // string  手机号 必需
					province: '', //string 省 必需
					provinceCode: '', // string 可选
					city: '', // string 市 必需
					cityCode: '', // string  必需
					area: '', //string 区 必需
					areaCode: '', // string 必需
					address: '', // string  详细地址 必需
					latitude: '', // string  必需 纬度，（六位小数，如24.412750）
					longitude: '', // string  必需 经度，（六位小数，如111.581652）
					is_default: 1, // integer  必需 设为默认：0否；1是 示例值: 1
				},
				rule: [
					{ name: "linkman",checkType: "notnull",checkRule: "",errorMsg: "请输入您真实姓名" },
					{ name: "phone",checkType: "notnull",checkRule: "",errorMsg: "请输入您手机号" },
					{ name: "province",checkType: "notnull",checkRule: "",errorMsg: "请选择所在地区" },
					{ name: "address",checkType: "notnull",checkRule: "",errorMsg: "请输入详细地址" },
					{ name: "is_default",checkType: "notnull",checkRule: "",errorMsg: "请选择是否默认地址" },
				],
				options7: [
					{ label: '否', value: 0 },
					{ label: '是', value: 1 },
				],
				editId: '', // string  必需 地址id
			};
		},
		onLoad(options) {
			this.editId = options.id
			if (this.editId) {
				this.getDetail()
			}
		},
		onShareAppMessage(){},
		onShareTimeline() {},
		methods: {
			// 获取详情
			getDetail() {
				this.$api.addressDetailsApi(this.editId).then(res=> {
					console.log('res', res);
					this.formData = res.data
				}).catch(err=> {
					console.log('err', err);
				})
			},
			// 删除
			handleDelete() {
				uni.showModal({
					title: '删除地址',
					content: '是否确认删除地址？',
					success: (res) => {
						if (res.confirm) {
							this.$api.addressDeleteApi(this.editId).then(res=> {
								uni.showToast({
									mask: true,
									title: '删除成功'
								})
								setTimeout(()=> {
									uni.navigateBack()
								}, 1200)
							}).catch(err=> {
								console.log('err', err);
							})
						}
					}
				})
			},
			// 提交
			submit() {
				const checkRes = checker.check(this.formData, this.rule);
				if (checkRes) {
					this.handleSubmit()
				} else {
					uni.showToast({
						title: checker.error,
						icon: "none"
					});
				}
			},
			handleSubmit() {
				if (this.editId) {
					this.$api.addressEditApi(this.editId, this.formData).then(res=> {
						uni.showToast({
							mask: true,
							title: '编辑成功'
						})
						setTimeout(()=> {
							uni.navigateBack()
						}, 1200)
					}).catch(err=> {
						console.log('err', err);
					})
					return
				}
				this.$api.addressCreateApi(this.formData).then(res=> {
					console.log('res', res);
					uni.showToast({
						mask: true,
						title: '添加成功'
					})
					setTimeout(()=> {
						uni.navigateBack()
					}, 1200)
				}).catch(err=> {
					console.log('err', err);
				})
			},
			// 选择区域
			handleSeleteArea(value) {
				this.formData.province = value.names[0] // string  省 可选
				this.formData.provinceCode = value.codes[0] // string  省编号 可选
				this.formData.city = value.names[1] // string  市 可选
				this.formData.cityCode = value.codes[1] // string  市编号 可选
				this.formData.area = value.names[2] // string  区/县 可选
				this.formData.areaCode = value.codes[2] // string  区/县编号 可选
				this.area = `${value.names[0]}/${value.names[1]}/${value.names[2]}`
			},
			openArea() {
				this.$refs.area.open()
			},
			changeType(item, key) {
				this.formData[key] = item.value
			},
			chooseLocation(status) {
				if (status || !this.formData.address) {
					uni.chooseLocation({
						success: (res)=> {
							const result = AddressParse.parse(res.address);
							this.formData.province = result[0].province
							this.formData.city = result[0].city
							this.formData.area = result[0].area
							
							this.formData.latitude = res.latitude
							this.formData.longitude = res.longitude
							this.formData.address = result[0].details + res.name
							
							this.getAreaCode()
						},
						fail: (err) => {
							console.log('err', err);
						}
					});
				}
			},
			getAreaCode() {
				const provinceIndex = provinceData.findIndex(item=> item.label === this.formData.province)
				const cityIndex = cityData[provinceIndex].findIndex(item=> item.label === this.formData.city)
				const areaIndex = areaData[provinceIndex][cityIndex].findIndex(item=> item.label === this.formData.area)
				
				if (provinceIndex !== -1 && provinceData[provinceIndex]) {
					this.formData.provinceCode = provinceData[provinceIndex].value
					
					if (cityIndex !== -1 && cityData[provinceIndex][cityIndex]) {
						this.formData.cityCode = cityData[provinceIndex][cityIndex].value
						
						if (areaIndex !== -1 && areaData[provinceIndex][cityIndex][areaIndex]) {
							this.formData.areaCode = areaData[provinceIndex][cityIndex][areaIndex].value
						}
					}
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.add-address {
		padding: 24rpx 32rpx;
		padding-bottom: calc(200rpx+ constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
		padding-bottom: calc(200rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/
		
		.form-card {
			padding: 32rpx;
			margin-bottom: 32rpx;
			border-radius: 12rpx;
			background-color: #FFFFFF;
		
			.card-title {
				font-size: 34rpx;
				font-weight: 600;
				text-align: left;
				line-height: 46rpx;
				padding-bottom: 32rpx;
				color: rgba(0, 0, 0, 1);
			}
		
			.sub-title {
				font-size: 26rpx;
				font-weight: 600;
				text-align: left;
				line-height: 48rpx;
				padding-left: 16rpx;
				color: rgba(0, 0, 0, 0.4);
			}
		
			.form {
				padding-top: 32rpx;
		
				.form-item {
					padding-bottom: 32rpx;
		
					&:last-child {
						padding-bottom: 0;
					}
				}
		
				.form-label {
					font-size: 28rpx;
					font-weight: 400;
					text-align: left;
					line-height: 44rpx;
					padding-bottom: 8rpx;
					color: rgba(0, 0, 0, 0.9);
				}
		
				.form-body {
					padding-bottom: 12rpx;
					border-bottom: 1px solid #E7E7E7;
				}
		
				.input {
					width: 100%;
					height: 72rpx;
					display: flex;
					align-items: center;
		
					input {
						flex: 1;
						height: 100%;
					}
				}
		
				.hint {
					font-size: 24rpx;
					font-weight: 400;
					text-align: left;
					line-height: 40rpx;
					padding-bottom: 10rpx;
					color: rgba(0, 0, 0, 0.4);
				}
		
				.right-btn {
					position: relative;
					padding: 0 32rpx;
					height: 48rpx;
					color: var(--primary-color);
					font-size: 32rpx;
					font-weight: 400;
					line-height: 48rpx;
					text-align: center;
					line-height: 48rpx;
		
					&:before {
						position: absolute;
						content: '';
						top: 5%;
						left: 0;
						bottom: 0;
						width: 1px;
						height: 90%;
						background-color: #E7E7E7;
					}
				}
				
				.radio-group {
					display: flex;
					flex-wrap: wrap;
					align-items: center;
					gap: 42rpx;
					flex-shrink: 0;
					min-height: 72rpx;
				
					.f-radio {
						font: 28rpx / calc(28rpx + 16rpx) PingFang SC, Microsoft YaHer, Arial Regular;
						color: var(--primary-color);
						box-sizing: border-box;
						margin: 0;
						padding: 0;
						list-style: none;
						position: relative;
						cursor: pointer;
						display: inline-block;
				
						.f-radio_former {
							border: 0;
							clip: rect(0 0 0 0);
							height: 1px;
							margin: -1px;
							overflow: hidden;
							padding: 0;
							position: absolute;
							width: 1px;
							outline: 0;
							appearance: none;
							display: none;
						}
				
						.f-radio_input {
							position: relative;
							display: inline-block;
							width: 18px;
							height: 18px;
							vertical-align: middle;
							border-radius: 999px;
							border: 1px solid #DCDCDC;
							background-color: #FFFFFF;
							transition: border .2s cubic-bezier(0, 0, .15, 1);
				
							&::after {
								position: absolute;
								content: "";
								top: 0;
								left: 0;
								right: 0;
								bottom: 0;
								width: 100%;
								height: 100%;
								opacity: 0;
								border-radius: 999px;
								box-sizing: border-box;
								border: 8rpx solid var(--primary-color);
								transition: all .2s cubic-bezier(0, 0, .15, 1);
							}
						}
				
						.f-radio_label {
							min-width: 56rpx;
							margin-left: 16rpx;
							white-space: nowrap;
							vertical-align: middle;
							display: inline-block;
							color: rgba(0, 0, 0, 0.9);
							font: 28rpx / calc(28rpx + 16rpx) PingFang SC, Microsoft YaHer, Arial Regular;
						}
					}
				
					.f-is-checked {
				
						.f-radio_input {
							border-color: var(--primary-color);
				
							&::after {
								opacity: 1;
							}
						}
					}
				}
			}
		}
		
		
	}
</style>
